﻿using UnityEngine;
using System.Collections;
using iTManager;
public class MapButton : MonoBehaviour
{
    [SerializeField]
    private tk2dTextMesh LevelTitle,PlayerScore;
	[SerializeField]
	private GameObject []objects_level;
	private Vector3 old_position;
	private OpenDialog buttonControl;
	private CloseDialog close;
	private GameManager manager;
	[SerializeField] 
	private tk2dSprite button_stop;
    [SerializeField]
    private AudioClip soundClip;
    private Levels levelObj=new Levels();
    
	void Start () {
		manager=GameManager.getInstance();
		old_position=objects_level[1].transform.position;
		buttonControl=new OpenDialog(objects_level);
		close=new CloseDialog(objects_level,old_position);
        DisableLevel();
	}
	public void ButtonClick(){
        if (manager.Sound)
        { PlaySound(); }

        if (this.gameObject.tag == "wheel_button")
        { manager.Wheel = true;
        }
        else if (this.gameObject.tag == "life")
        { buttonControl.Action();
        return;
        }
        else
        {
			LevelTitle.text = "Level " + objects_level[3].name.ToString();
			manager.currentLevel = int.Parse(objects_level[3].name);
            
        }
        buttonControl.Action();
        if (manager.lastLevel >= manager.currentLevel) {
			if(PlayerScore!=null){
            	PlayerScore.gameObject.SetActive(true);
            	PlayerScore.text="Your Score: \n"+ (PlayerPrefs.GetInt(manager.currentLevel.ToString())).ToString();
			}
        }
	}
	private void CloseClick(){
        if (manager.Sound)
        { PlaySound(); }
        StartCoroutine(loadNextScene());
        if (this.gameObject.tag == "close_wheel")
        {
            WheelAni.i = 2;
            button_stop.collider.enabled = true;
            button_stop.SetSprite("stop");
        }
	}
    void PlaySound()
    {
        audio.clip = soundClip;
        audio.Play();
    }
    private IEnumerator loadNextScene()
    {
        yield return new WaitForSeconds(0.5f);
        close.Action();
    }
    public void DisableLevel()
	{	
		if (objects_level.Length==2) { return; }
        manager.lastLevel = PlayerPrefs.GetInt("lastlevel");
        if (manager.lastLevel == 0)
        {
            manager.lastLevel = 1;
        } 
		if (int.Parse(objects_level[3].name) > manager.lastLevel)
        {
			objects_level[3].transform.renderer.enabled = false;
			objects_level[2].transform.GetComponent<BoxCollider>().enabled = false;
        }
    }
}
